package com.lzy.dao.im;

import java.util.List;


import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Component;

import com.lzy.dao.HibernateDao;
import com.lzy.entity.IMTask;
import com.lzy.util.Constants.TaskType;
import com.lzy.util.Page;
import com.lzy.util.PageRequest;

@Component
public class IMTaskDaoImpl extends HibernateDao implements IMTaskDao{

	public void addIMTask(IMTask imTask) {
		Session session = sessionFactory.getCurrentSession();
		session.save(imTask);
	}

	public void delIMTask(int... taskId) {
		Session session = sessionFactory.getCurrentSession();
		for (int i = 0; i < taskId.length; i++) {
			IMTask imTask = (IMTask)session.load(IMTask.class, taskId[i]);
			session.delete(imTask);
		}
	}

	public Page<IMTask> getIMTaskList(PageRequest pageRequest) {
		Session session = sessionFactory.getCurrentSession();
		Page<IMTask> page = new Page<IMTask>(pageRequest);
		Query query = session.createQuery("from IMTask order by CreateTime desc");
		query.setFirstResult(pageRequest.getStart());
		query.setFetchSize(pageRequest.getLimit());
		List<IMTask> list = query.list();
		page.setResult(list);
		page.setTotalItems(list.size());
		return page;
	}

	public Page<IMTask> getIMTaskListByState(PageRequest pageRequest,String states) {
		Session session = sessionFactory.getCurrentSession();
		Page<IMTask> page = new Page<IMTask>(pageRequest);
		Query query = session.createQuery("from IMTask where status in(" + states +") order by CreateTime desc ");
		query.setFirstResult(pageRequest.getStart());
		query.setFetchSize(pageRequest.getLimit());
		List<IMTask> list = query.list();
		page.setResult(list);
		page.setTotalItems(list.size());
		return page;
	}
	
	public void updateIMTask(IMTask imTask) {
		Session session = sessionFactory.getCurrentSession();
		session.update(imTask);
	}
	
	public IMTask queryIMTask(int taskId) {
		Session session = sessionFactory.getCurrentSession();
		IMTask imTask = (IMTask)session.get(IMTask.class, taskId);
		return imTask;
	}
	
	public void startIMTask(int... taskId) {
		Session session = sessionFactory.getCurrentSession();
		for (int i = 0; i < taskId.length; i++) {
			IMTask imTask = (IMTask)session.load(IMTask.class, taskId[i]);
			imTask.setStatus(TaskType.waiting.value());
			session.update(imTask);
		}
	}
	
	public void stopIMTask(int... taskId) {
		Session session = sessionFactory.getCurrentSession();
		for (int i = 0; i < taskId.length; i++) {
			IMTask imTask = (IMTask)session.load(IMTask.class, taskId[i]);
			imTask.setStatus(TaskType.created.value());
			session.update(imTask);
		}
	}
	
}
